package com.lyl.quartz.test;

import com.lyl.quartz.jobs.HelloJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 多个trigger调用一个job
 * @author lylbell
 * @date 2022-03-29 10:35
 */
public class _02_QuartzTest_MultTrigger2 {

    public static void main(String[] args) throws SchedulerException, InterruptedException {

        // 调度器工厂创建默认调度器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // 启动调度器
        scheduler.start();

        // 创建job。加了storeDurably()
        JobDetail job = JobBuilder.newJob(HelloJob.class).storeDurably().withIdentity("job1", "group1").build();

        // 创建trigger。withIntervalInSeconds：每5秒执行一次。
        // repeatForever：一直重复执行
        // 执行5次。0 1 2 3
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .startNow()
                .forJob(job)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever()).build();


        // forJob:指定job
        // 0 3
        Trigger trigger2 = TriggerBuilder.newTrigger()
                .withIdentity("trigger2", "group1")
                .startNow()
                .forJob(job)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever()).build();


        // trigger1和trigger2都指定job。.forJob(job)
        // job加了storeDurably() 。不然会报错：Jobs added with no trigger must be durable.
        scheduler.addJob(job,true);
        scheduler.scheduleJob(trigger);
        scheduler.scheduleJob(trigger2);


        // 执行3秒
        TimeUnit.SECONDS.sleep(3);

        scheduler.shutdown();
    }
}
